package com.hmall.gateway.filter;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
@RequiredArgsConstructor
public class AuthFilter implements GlobalFilter , Ordered {

    private final JwtTool jwtTool;

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        log.debug("拦截器生效");
        //获取Request
        ServerHttpRequest request = exchange.getRequest();
        //判断是否拦截
        if(isExclude(request.getPath().toString()))
        {
            return chain.filter(exchange);
        }
        //获取用户
        String token = request.getHeaders().getFirst("authorization");
        Long userId= null;
        try {
            userId = jwtTool.parseToken(token);
        }
        catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        log.debug("用户 id :{}",userId);
        String userInfo = userId.toString();
        //修改请求头，将用户信息传到下游
        ServerWebExchange build = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo)).build();
        //放行
        return chain.filter(build);
    }

    private boolean isExclude(String string) {
        for(String s: authProperties.getExcludePaths())
        {
            if(antPathMatcher.match(s, string))
            {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
